import Axios, {
  type AxiosInstance,
  type AxiosError,
  type AxiosResponse,
  type AxiosRequestConfig
} from "axios";
import { ContentTypeEnum, ResultEnum } from "@/enums/request-enum";
import NProgress from "../progress";
import { showFailToast } from "vant";
import "vant/es/toast/style";

// 默认 axios 实例请求配置
const configDefault = {
  headers: {
    "Content-Type": ContentTypeEnum.JSON
  },
  timeout: 0,
  baseURL: import.meta.env.VITE_BASE_API,
  data: {}
};

class Http {
  // 当前实例
  private static axiosInstance: AxiosInstance;
  // 请求配置
  private static axiosConfigDefault: AxiosRequestConfig;

  // 请求拦截
  private httpInterceptorsRequest(): void {
    Http.axiosInstance.interceptors.request.use(
      config => {
        NProgress.start();
        config.headers["auth-appid"] = "wxbef4428ce1c6b502";
        config.headers["channel-type"] = "310";
        config.headers["x-requested-version"] = "feature/v202505-saas";
        config.headers["authorization"] =
          "Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJja2pyIiwiZXhwIjoxNzU1OTMxOTQ0LCJuYmYiOjE3NTMzMzk5NDQsImlhdCI6MTc1MzMzOTk0NCwicmZ0IjoxNzU1ODQ1NTQ0LCJzdWIiOiJtcF9sb2dpbiIsInVpZCI6IjE4Nzk3Njc1ODYyMDQxNDM2MTciLCJqdXQiOiIxIiwiY2h0IjoiMzEwIiwiY2lkIjoiMSJ9.g4Z7zcR6vrzrF9WkzUImH5UROOy552ofENZYejmDK-E";
        return config;
      },
      (error: AxiosError) => {
        showFailToast(error.message);
        return Promise.reject(error);
      }
    );
  }

  // 响应拦截
  private httpInterceptorsResponse(): void {
    Http.axiosInstance.interceptors.response.use(
      (response: AxiosResponse) => {
        NProgress.done();
        // 与后端协定的返回字段
        const { statusCode, data } = response.data;
        // 判断请求是否成功
        const isSuccess =
          Reflect.has(response.data, "statusCode") &&
          statusCode === ResultEnum.SUCCESS;
        if (isSuccess) {
          return data;
        } else {
          // 处理请求错误
          const { msg = "未知错误" } = response.data;
          showFailToast(msg);
          return Promise.reject(msg);
        }
      },
      (error: AxiosError) => {
        NProgress.done();
        console.log(error.response?.data);
        const data = error.response?.data || {};
        const { msg = "请求失败，请稍后再试" } = data as { msg?: string };
        showFailToast(msg);
        return Promise.reject(error);
      }
    );
  }

  constructor(config: AxiosRequestConfig) {
    Http.axiosConfigDefault = config;
    Http.axiosInstance = Axios.create(config);
    this.httpInterceptorsRequest();
    this.httpInterceptorsResponse();
  }

  // 通用请求函数
  public request<T>(paramConfig: AxiosRequestConfig): Promise<T> {
    const config = { ...Http.axiosConfigDefault, ...paramConfig };
    return new Promise((resolve, reject) => {
      Http.axiosInstance
        .request(config)
        .then((response: any) => {
          resolve(response);
        })
        .catch(error => {
          reject(error);
        });
    });
  }
}

export const http = new Http(configDefault);
